package com.example.demo.component;

import com.example.demo.api.WebSocketAPI;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class OnlineUserManage {

//    记录用户在线的状态
    private ConcurrentHashMap<Integer, WebSocketSession> sessions=new ConcurrentHashMap<>();
//    1.用户上线,新增元素
    public void online(int userId, WebSocketSession session){
        if(sessions.get(userId)!=null){
            return;
        }
        sessions.put(userId,session);
        System.out.println(userId+"上线 ");
    }
//    2.用户下线,删除元素
    public void offline(int userId,WebSocketSession session){
        WebSocketSession existSession=sessions.get(userId);
        if(existSession==session){
            sessions.remove(userId);
            System.out.println(userId+"下线");
        }


    }
//    根据userI获取webSocketSession
    public WebSocketSession getSession(int userId){
        return sessions.get(userId);
    }
}
